package com.me.videoservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.me.videoservice.model.entry.DeviceInfo;
import com.me.videoservice.model.msg.MqttDisconnectedMsg;
import com.me.videoservice.service.DeviceInfoService;
import com.me.videoservice.service.MqttService;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
public class MqttDeviceDisconnectedServiceImpl implements MqttService {

  @Autowired
  private DeviceInfoService deviceInfoService;

  @Override
  public Boolean topic(String topic) {
    return topic.matches("\\$SYS/brokers/.*/clients/.*/disconnected");
  }

  @Override
  public void process(Message<?> message, String topic) {
    MqttDisconnectedMsg msg = JSON
        .parseObject((String) message.getPayload(), MqttDisconnectedMsg.class);
    deviceInfoService.lambdaUpdate()
        .set(DeviceInfo::getOfflineFlag, 2)
        .set(DeviceInfo::getUpdatedAt, LocalDateTime.now())
        .eq(DeviceInfo::getDeviceId, msg.getClientId()).update();
  }

}
